//
//  AppDelegate.m
//  Test passenger soldier
//
//  Created by ikuaiyue on 15/7/4.
//  Copyright (c) 2015年 shike. All rights reserved.
//
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#import "AppDelegate.h"
#import "ViewController.h"
#import "MMPDeepSleepPreventer.h"
#import <AdSupport/AdSupport.h>
#import "WXApi.h"
#import "AFNTool.h"
#import "HttpUtil.h"
#import "OpenUDID.h"
#import "UIDevice+IdentifierAddition.h"
#import "SecureUDID.h"
#import "WQUserDataManager.h"
#import <Security/Security.h>
#import "CoreTelephony.h"
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>

//#define mainHttp @"http://www.apptyk.com"
#define mainHttp @"http://112.74.219.188"



static NSString *appKey = @"3f87259a432a5ec608e9e473";
static NSString *channel = @"Publish channel";
static BOOL isProduction = FALSE;

@interface AppDelegate ()<WXApiDelegate,UIAlertViewDelegate>
{
    NSArray *_arr;
    NSString *str;
    UIImage *_shareImage;
    NSString *_DetailUrl;
    NSString *urls;
    NSString *downStr;
    UIAlertView *_alertView;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    
    if ([self isJailBreak]) {
        UIAlertView *alret = [[UIAlertView alloc]initWithTitle:@"提示" message:@"越狱机器无法做任务" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alret.delegate = self;
        alret.tag = 1001;
        [alret show];
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isJailBreak"];
    }
    
    ViewController *cvc = [[ViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:cvc];
    self.window.rootViewController = cvc;
    MMPDeepSleepPreventer * soundBoard =   [MMPDeepSleepPreventer new];
    [soundBoard startPreventSleep];
    
    
    
   
    LOG(@"%@",[SecureUDID UDIDForDomain:@"com.example.myapp" usingKey:@"difficult-to-guess-key"]);
   
    
    NSLog(@"%@",DATABASE_PATH);
    LOG(@"%@",[OpenUDID value]);
    NSLog(@"%@",[ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString);
    NSLog(@"%@", [UIDevice currentDevice].model);
    LOG(@"%@",[[[UIDevice currentDevice]identifierForVendor] UUIDString]);
    
    [WXApi registerApp:@"wxf50b93a7184c9e5d" withDescription:@"weixin ifeimeng"];
    
    LOG(@"---%@",[[UIDevice currentDevice] uniqueDeviceIdentifier]);
    LOG(@"---%@",[[UIDevice currentDevice] uniqueGlobalDeviceIdentifier]);
    if (![WQUserDataManager readPassWord]) {
        [WQUserDataManager savePassWord:[ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString];
    }
    LOG(@"%@",[WQUserDataManager readPassWord]);
    UIDevice *myDevice = [[UIDevice alloc]init];
  
    LOG(@"%@",[self macaddress]);
//    struct CTResult result;
//    NSString *imei;
//    struct CTServerConnection *sc = _CTServerConnectionCreate(kCFAllocatorDefault,(__bridge void*)self, NULL);
//    _CTServerConnectionCopyMobileIdentity(&result, sc, &imei);
//    
//    if (imei.length == 14) {
//        imei = [imei stringByAppendingString:@"0"];
//    }
//    LOG(@"%@",imei);
    
    return YES;
}
- (NSString *) macaddress
{
    
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);
    return address;
}
- (BOOL)isJailBreak
{
    const char* jailbreak_tool_pathes[] = {
        "/Applications/Cydia.app",
        "/Library/MobileSubstrate/MobileSubstrate.dylib",
        "/bin/bash",
        "/usr/sbin/sshd",
        "/etc/apt"
    };
    for (int i=0; i<ARRAY_SIZE(jailbreak_tool_pathes); i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jailbreak_tool_pathes[i]]]) {
            NSLog(@"The device is jail broken!");
            return YES;
        }
    }
    NSLog(@"The device is NOT jail broken!");
    return NO;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    LOG(@"%@",url);
    NSString *urlStr = [NSString stringWithFormat:@"%@",url];
    //wxifeimeng://url=qq://
    urls  =[NSString stringWithFormat:@"%@",url];
    if ([urls rangeOfString:@"shared"].length) {
        
        [self performSelector:@selector(afterss) withObject:self afterDelay:2.0];
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"shared"];
        
    }else if([urls rangeOfString:@"wxshangfei"].length)
    {
        if (urls.length > 14) {
        _arr  = [urls componentsSeparatedByString:@"="];
        if (_arr.count>0) {
            NSString *paramsStr = [urlStr substringWithRange:NSMakeRange(13, urlStr.length -13)];
            
            [[NSUserDefaults standardUserDefaults]setObject:paramsStr forKey:@"paramsStr"];
            NSLog(@"%@",paramsStr);
            [self performSelector:@selector(after) withObject:self afterDelay:2.0];
        }
        }
    }else
    {
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urls]];
    }
    return  [WXApi handleOpenURL:url delegate:self];

    
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

-(void)afterss
{
    NSArray *arrOne = [urls componentsSeparatedByString:@"wxshangfei://"];
    NSArray *arrTow = [arrOne[1] componentsSeparatedByString:@"&"];
    
    _shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[arrTow[2] componentsSeparatedByString:@"="][1]]]];
//    str = [arrTow[3] componentsSeparatedByString:@"="][1];
    
    NSData*jsondata = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString*   temp = [[NSString alloc] initWithData:jsondata encoding:encoding];
    
    LOG(@"%@",(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, nil, nil, kCFStringEncodingUTF8)));
    
    
    _DetailUrl = [arrTow[1] componentsSeparatedByString:@"="][1];
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"shared"];
    if ([[arrTow[0] componentsSeparatedByString:@"="][1] integerValue] == 1) {
        [self sendTextContent];
    }else
    {
        [self sendLinkContent];
    }

}
#pragma mark weiXin
- (void)sendTextContent
{
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"每3分钟就可以完成一个任务即可获得1到2元的奖励";
    message.description = @"每3分钟就可以完成一个任务即可获得1到2元的奖励";
    [message setThumbImage:_shareImage];
    WXWebpageObject *ext = [WXWebpageObject object];
    
    ext.webpageUrl = [NSString stringWithFormat:@"%@?unionid=%@",_DetailUrl,[[NSUserDefaults standardUserDefaults] objectForKey:@"unionid"]];
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;
    
    [WXApi sendReq:req];
    
    
    
}
-(void)sendLinkContent
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"";
    message.description = @"每3分钟就可以完成一个任务即可获得1到2元的奖励";
    [message setThumbImage:_shareImage];
    WXWebpageObject *ext = [WXWebpageObject object];
    LOG(@"%@",[NSString stringWithFormat:@"%@?unionid=%@",_DetailUrl,[[NSUserDefaults standardUserDefaults] objectForKey:@"unionid"]]);
    ext.webpageUrl = [NSString stringWithFormat:@"%@?unionid=%@",_DetailUrl,[[NSUserDefaults standardUserDefaults] objectForKey:@"unionid"]];
    message.mediaObject = ext;
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    
    [WXApi sendReq:req];
}


-(void)after
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_arr[1]]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"getDate" object:nil];
}

- (void)wxlogin
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_arr[1]]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"getDate" object:nil];
}

-(void)onResp:(BaseResp *)resp
{
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *strTitle = [NSString stringWithFormat:@"提示"];
        
        NSString *strMsg = nil;
        if (resp.errCode == 0) {
            strMsg = @"分享成功";
            [[NSNotificationCenter defaultCenter] postNotificationName:@"sharedSuccess" object:nil];
        }else
        {
            strMsg = @"分享失败";
        }
        
    }else if ([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *resps =(SendAuthResp *)resp;
        __block NSString *prepayIdUrl = [NSString stringWithFormat:@"sns/oauth2/access_token?appid=%@",WXAppId];
        __block ViewController *cvc = (ViewController *)self.window.rootViewController;
        NSMutableDictionary *parames = [NSMutableDictionary dictionary];
        
        if (resps.code !=nil) {
            LOG(@"%@",resps.code);
            [parames setObject:resps.code forKey:@"code"];
        }
        [parames setObject:WXAppSecret forKey:@"secret"];
        [parames setObject:@"authorization_code" forKey:@"grant_type"];
        [cvc.visiblebtn setTitle:@"验证中..." forState:UIControlStateNormal];
        [HttpUtil doGetWithUrl:@"https://api.weixin.qq.com/" path:prepayIdUrl params:parames callback:^(BOOL isSuccessed, NSDictionary *result) {
            LOG(@"%@",result);
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            //        if ([result objectForKey:@"unionid"]) {
            //            [dic setObject:[result objectForKey:@"unionid"] forKey:@"unionid"];
            //        }
            if ([WQUserDataManager readPassWord]) {
                [dic setObject:[WQUserDataManager readPassWord] forKey:@"deviceid"];
            }
            
            [dic setObject:[ASIdentifierManager sharedManager].advertisingIdentifier forKey:@"idfa"];
            [dic setObject:[UIDevice currentDevice].model forKey:@"model"];
            if (![result objectForKey:@"access_token"]) {
                return ;
            }
            prepayIdUrl = [NSString stringWithFormat:@"sns/userinfo?access_token=%@",[result objectForKey:@"access_token"]];
            NSMutableDictionary *parames = [NSMutableDictionary dictionary];
            [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"unionid"] forKey:@"unionid"];
            [parames setObject:[result objectForKey:@"unionid"] forKey:@"unionid"];
            [parames setObject:[result objectForKey:@"openid"] forKey:@"openid"];
            [HttpUtil doGetWithUrl:@"https://api.weixin.qq.com/" path:prepayIdUrl params:parames callback:^(BOOL isSuccessed, NSDictionary *result) {
                if ([result objectForKey:@"headimgurl"]) {
                    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"headimgurl"] forKey:@"headimgurl"];
                }
                if ([result objectForKey:@"nickname"]) {
                    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"nickname"] forKey:@"nickname"];
                }
                
                //            cvc.nameLabel.text = [result objectForKey:@"nickname"];
                //            [cvc.headImageView  setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[result objectForKey:@"headimgurl"]]]]];
                
                LOG(@"%@",result);
                
                [dic setObject:[result objectForKey:@"unionid"] forKey:@"unionid"];
                [dic setObject:[result objectForKey:@"headimgurl"] forKey:@"headimgurl"];
                [dic setObject:[result objectForKey:@"nickname"] forKey:@"nickname"];
                [dic setObject:[result objectForKey:@"openid"] forKey:@"openid"];
                [dic setObject:[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] forKey:@"idfa"];
                
                [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/check",mainHttp] dic:dic view:nil success:^(id json) {
                    LOG(@"%@",json);
                    if (![json isKindOfClass:[NSArray class]]) {
                        
                        if (json[@"url"]) {
                            
                            NSString *url = [NSString stringWithFormat:@"%@",json[@"url"]];
                            LOG(@"%@",url);
                            [[NSUserDefaults standardUserDefaults] setObject:url forKey:@"url"];
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
                        }
                        [[NSUserDefaults standardUserDefaults] setObject:json[@"userid"] forKey:@"UID"];
                        [[NSUserDefaults standardUserDefaults] setObject:json[@"accountid"] forKey:@"accountid"];
                        cvc.nameLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"nickname"];
                        //                    [cvc.headImageView  setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:@"headimgurl"]]]]];
                        [cvc.visiblebtn setTitle:@"验证通过" forState:UIControlStateNormal];
                        [cvc.showBtn setImage:[UIImage imageNamed:@"试玩过程中请保持粉咖后台运行"] forState:UIControlStateNormal];
                        [cvc.loginBtn setTitle:@"返回粉咖" forState:UIControlStateNormal];
                        
                    }else
                    {
                        [cvc.visiblebtn setTitle:@"未认证" forState:UIControlStateNormal];
                        [cvc.loginBtn setTitle:@"微信登录认证" forState:UIControlStateNormal];
                    }
                    
                    
                } failure:^(NSError *error) {
                    [cvc.visiblebtn setTitle:@"未认证" forState:UIControlStateNormal];
                    [cvc.loginBtn setTitle:@"微信登录认证" forState:UIControlStateNormal];
                    LOG(@"%@",error.localizedDescription);
                }];
            }];

                
            }];
        
            
            
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^(){
        
        //程序在10分钟内未被系统关闭或者强制关闭，则程序会调用此代码块，可以在这里做一些保存或者清理工作
        
        NSDictionary *dict = [NSDictionary  dictionary];
        
        [dict setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
        
        [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/off-line",mainHttp] dic:dict view:nil success:^(id json) {
            LOG(@"%@",json);
            
        } failure:^(NSError *error) {
            
        }];

    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//    [AFNTool initYaoYues:[NSString stringWithFormat:@"%@/api/version-update",mainHttp] dic:nil view:nil success:^(id json) {
//        LOG(@"%@",json);
//        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
//        if (![[NSString stringWithFormat:@"%@",json[@"version"]] isEqualToString:[infoDic objectForKey:@"CFBundleVersion"]]) {
//            downStr = json[@"url"];
//            if (!_alertView) {
//                _alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"粉咖有更新，为了保证成功完成任务请去更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//                [_alertView show];
//            }
//           
//        }
//    } failure:^(NSError *error) {
//        
//    }];
    [self getState:@"1"];
    
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001) {
        if (buttonIndex == 0) {
            exit(1);
        }
    }else{
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:downStr]];
        }
    }
    
}
-(void)getState:(NSString *)state
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"UID"]) {
        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UID"] forKey:@"uid"];
        [dic setObject:state forKey:@"isOnline"];
    }else
    {
        return;
    }
    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/is-online",mainHttp] dic:dic view:nil success:^(id json) {
        LOG(@"%@",json);
    } failure:^(NSError *error) {
        
    }];
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSMutableDictionary *dict = [NSMutableDictionary  dictionary];
    
    NSString *str1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    [dict setObject:str1 forKey:@"uid"];
    
    [AFNTool initYaoYue:[NSString stringWithFormat:@"%@/api/off-line",mainHttp] dic:dict view:nil success:^(id json) {
        LOG(@"%@",json);
        
    } failure:^(NSError *error) {
        
    }];
}


@end
